package tool

import (
	"log"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/mongo"
	"github.com/gin-gonic/gin"
	"github.com/globalsign/mgo"
)

func InitSessionStore(router *gin.Engine) {

	config := GetConfig().MongodbConfig
	session, err := mgo.Dial(config.Host + ":" + config.Port + "/" + config.DbName)
	if err != nil {
		log.Fatalln(err.Error())
		return
	}

	c := session.DB("").C("sessions")
	store := mongo.NewStore(c, 3600, true, []byte("secret"))

	router.Use(sessions.Sessions("mysession", store))

	// router.GET("/setsession", func(c *gin.Context) {
	// 	session := sessions.Default(c)
	// 	var count int
	// 	v := session.Get("count")
	// 	if v == nil {
	// 		count = 0
	// 	} else {
	// 		count = v.(int)
	// 		count++
	// 	}
	// 	session.Set("count", count)
	// 	session.Save()
	// 	c.JSON(200, gin.H{"count": count})
	// })

}

// 设置 session 并保存到 mongodb
func SetSession(c *gin.Context, key interface{}, value interface{}) error {
	session := sessions.Default(c)

	if session == nil {
		return nil
	}

	session.Set(key, value) // 设置 session
	return session.Save()   // 保存到 mongodb
}

// 获取指定的 key 的 session 值
func GetSession(c *gin.Context, key interface{}) interface{} {
	session := sessions.Default(c)

	return session.Get(key) // 获取 session
}
